package com.example.bookshop.mapper;

import com.example.bookshop.entity.Book;
import org.apache.ibatis.annotations.*;

import java.util.List;

/**
 * @auth shanyue
 * @date 2025年06月04日16:02
 */
@Mapper
public interface BookMapper {

    @Select("SELECT * FROM books")
    List<Book> findAll();

    @Select("SELECT * FROM books WHERE id = #{id}")
    Book findById(int id);

    @Insert("INSERT INTO books(title, author, price, stock) VALUES(#{title}, #{author}, #{price}, #{stock})")
    void insert(Book book);

    @Update("UPDATE books SET stock = #{stock} WHERE id = #{id}")
    void update(Book book);

    @Select("<script>" +
            "SELECT * FROM books " +
            "<where> " +
            "  <if test='keyword != null and keyword != \"\"'> " +
            "    (title LIKE CONCAT('%', #{keyword}, '%') OR author LIKE CONCAT('%', #{keyword}, '%')) " +
            "  </if> " +
            "</where> " +
            "ORDER BY id ASC " +
            "LIMIT #{offset}, #{size} " +
            "</script>")
    List<Book> searchBooks(@Param("keyword") String keyword,
                           @Param("offset") int offset,
                           @Param("size") int size);

    @Select("<script>" +
            "SELECT COUNT(*) FROM books " +
            "<where> " +
            "  <if test='keyword != null and keyword != \"\"'> " +
            "    (title LIKE CONCAT('%', #{keyword}, '%') OR author LIKE CONCAT('%', #{keyword}, '%')) " +
            "  </if> " +
            "</where>" +
            "</script>")
    int countBooks(@Param("keyword") String keyword);

    @Update("UPDATE books SET title=#{title}, author=#{author}, price=#{price}, stock=#{stock} WHERE id=#{id}")
    void updateBook(Book book);

    @Delete("DELETE FROM books WHERE id = #{id}")
    void deleteById(Integer id);
}
